﻿using System;
using Microsoft.SharePoint;

namespace Redirection
{
    public class PropertyBagHelper
    {
        public static T LoadValues<T>(SPWeb web, string propKey)
        {
            T value = default(T);

            object propbagItem = web.AllProperties[propKey];

            if (propbagItem != null)
            {
                value = (T) Convert.ChangeType(propbagItem.ToString(), typeof (T));
            }

            return value;
        }

        public static void SaveValues<T>(SPWeb web, string propKey, T value)
        {
            bool updates = web.AllowUnsafeUpdates;

            if (!updates)
            {
                web.AllowUnsafeUpdates = true;
            }

            if (!web.AllProperties.ContainsKey(propKey))
            {
                web.AllProperties.Add(propKey, value);
            }
            else
            {
                web.AllProperties[propKey] = value;
            }

            web.Update();

            if (!updates)
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}